<script setup>
import { Delete, Edit } from "@element-plus/icons-vue";
import { ref } from "vue";
import ChannelSelect from "./components/ChannelSelect.vue";
import BookEdit from "./components/BookEdit.vue";
import { listBook, deleteBook } from "@/api/book/index";
const loading = ref(false); // loading状态
const bookEditRef = ref();

const formatPrice = (price) => {
  if (price == null) return "免费";
  const num = typeof price === "number" ? price : parseFloat(price);
  return isNaN(num) ? "0.00 元" : num.toFixed(2) + " 元";
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")} ${String(
    date.getHours()
  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
};

// 定义请求参数对象
const params = ref({
  pageNum: 1, // 当前页
  pageSize: 5, // 当前生效的每页条数
  categoryId: "",
});

const total = ref(0); // 总条数
const bookList = ref([]); // 文章列表

// 基于params参数，获取文章列表
const getBookList = async () => {
  loading.value = true;
  const res = await listBook(params.value);
  const bookData = res.data.data; // 这是包含 total 和 data 的对象
  bookList.value = bookData.data; // 取出真正的数据数组
  total.value = bookData.total;
  loading.value = false;
};
getBookList();

const onSizeChange = (size) => {
  params.value.pageNum = 1;
  params.value.pageSize = size;
  getBookList();
};
const onCurrentChange = (page) => {
  params.value.pageNum = page;
  getBookList();
};

const onSearch = () => {
  params.value.pagenum = 1; // 重置页面
  getBookList();
};

// 重置逻辑 => 将筛选条件清空，重新检索，从第一页开始展示
const onReset = () => {
  params.value.pageNum = 1; // 重置页面
  params.value.categoryId = "";
  getBookList();
};

const onDeleteBook = async (row) => {
  await ElMessageBox.confirm("你确认删除该文章信息吗？", "温馨提示", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  });
  await deleteBook(row.id);
  ElMessage({ type: "success", message: "删除成功" });
  getBookList();
};

// 编辑新增逻辑
const onAddArticle = () => {
  bookEditRef.value.open({});
};
const onEditArticle = (row) => {
  bookEditRef.value.open(row);
};

// 添加或者编辑 成功的回调
const onSuccess = (type) => {
  if (type === 'add') {
    // 如果是添加，最好渲染最后一页
    const lastPage = Math.ceil((total.value + 1) / params.value.pageSize)
    // 更新成最大页码数，再渲染
    params.value.pageNum = lastPage
  }

  getBookList()
}
</script>

<template>
  <page-container title="图书管理">
    <template #extra>
      <el-button type="primary" @click="onAddArticle">添加图书</el-button>
    </template>

    <el-form inline>
      <el-form-item label="图书分类：">
        <channel-select v-model="params.categoryId" />
      </el-form-item>

      <el-form-item>
        <el-button @click="onSearch" type="primary">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table :data="bookList" style="width: 100%">
      <el-table-column label="图书标题" width="400">
        <template #default="{ row }">
          <el-link type="primary" :underline="false">{{ row.name }}</el-link>
        </template>
      </el-table-column>

      <el-table-column label="分类" prop="categoryName" />

      <el-table-column label="价格" prop="price">
        <template #default="{ row }">
          {{ formatPrice(row.price) }}
        </template>
      </el-table-column>

      <el-table-column label="发表时间" prop="createTime">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="onEditArticle(row)"
          />
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="onDeleteBook(row)"
          />
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[2, 3, 5, 10]"
      :background="true"
      layout="jumper, total, sizes, prev, pager, next"
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 弹窗 -->
    <book-edit ref="bookEditRef" @success="onSuccess"></book-edit>
  </page-container>
</template>

<style lang="scss" scoped></style>